package com.kaifamiao.jsp.servlet;

import com.kaifamiao.jsp.entity.Customer;
import com.kaifamiao.utils.JdbcHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.logging.Logger;

@WebServlet( "/customer/remove" )
public class CustomerRemoveServlet extends HttpServlet {

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    protected void service(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        final String listURL = request.getContextPath() + "/customer/list" ;

        String id = request.getParameter( "id" );
        logger.info( "准备删除[" + id + "]对应的客户信息" );

        Integer cid = Integer.valueOf( id );

        HttpSession session = request.getSession();
        Customer c = (Customer) session.getAttribute( "customer" );

        if( c.getId().equals( cid ) ){
            session.setAttribute( "message" , "自己不能删除自己" );
            response.sendRedirect( listURL );
            return ;
        }

        JdbcHelper helper = JdbcHelper.getInstance();
        String sql = "DELETE FROM t_customers WHERE id = ? ";
        int count = helper.execute( sql , cid );
        if( count != 1 ) {
            session.setAttribute( "message" , "删除失败" );
            response.sendRedirect( listURL );
            return ;
        }

        session.setAttribute( "message" , "删除成功" );
        response.sendRedirect( listURL );
    }

}
